package com.bitland.demo.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bitland.demo.api.ResultMsg;
import com.bitland.demo.api.entity.Star;
import com.bitland.demo.api.service.StarService;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * ********************************************************
 *
 * @Author:Joe
 * @Date:Created in 11:32    2020/8/10
 * @Description: mybatisplus的测试类
 * <p>
 * ********************************************************
 */
@RestController
@RequestMapping("/stars")
public class MybatisPlusController {

    @Resource
    private StarService starService;

    /**
     * @Author:Joe
     * @Date:Created in 15:11  2020/8/10
     * @Description: 数据插入
     */
    @PostMapping
    public ResultMsg insert(@RequestBody @Validated Star star){
        starService.save(star);
        return ResultMsg.SUCCESS(star);
    }


    /**
     * @Author:Joe
     * @Date:Created in 15:12  2020/8/10
     * @Description: 更新数据
     */
    @PatchMapping("/{id}")
    public ResultMsg update(@RequestBody @Validated Star star){
        starService.updateById(star);
        return ResultMsg.SUCCESS;
    }
    /**
     * @Author:Joe
     * @Date:Created in 15:42  2020/8/10
     * @Description: 局部更新
     */
    @DeleteMapping("/{id}")
    public ResultMsg remove(@RequestBody @Validated Star star,@PathVariable("id") String id){
        starService.removeById(id);
        return ResultMsg.SUCCESS;
    }
    /**
     * @Author:Joe
     * @Date:Created in 15:15  2020/8/10
     * @Description: 逻辑删除数据
     */
    @DeleteMapping("/logic/{id}")
    public ResultMsg delete(@PathVariable("id") String id){
        starService.getBaseMapper().deleteById(id);
        return ResultMsg.SUCCESS;
    }

    /**
     * @Author:Joe
     * @Date:Created in 15:17  2020/8/10
     * @Description: 列表
     */
    @PostMapping("/{pageNum}_{pageSize}")
    public ResultMsg list(@RequestBody Star star,
                          @PathVariable("pageNum") int pageNum,@PathVariable("pageSize") int pageSize){
        Page page = starService.page(new Page(pageNum, pageSize), new QueryWrapper<Star>()
                .like(StringUtils.isNotEmpty(star.getStarName()), "star_name", star.getStarName())
                .eq(star.getGender() != null, "gender", star.getGender())
                .gt(star.getPublishBeginTime() != null,"publish_time",star.getPublishBeginTime())
                .lt(star.getPublishEndTime() != null,"publish_time",star.getPublishEndTime())
                .orderByDesc("publish_time")
        );
        return ResultMsg.SUCCESS(page);
    }
}
